import { View, Image, Text } from '@tarojs/components'
import { useState, useEffect } from 'react'
import LgButton from '@/pages/components/button'
import Header from '@/pages/messageApp/component/header'
import Taro, { Current } from '@tarojs/taro'
import { requestSystemUrl } from '@/network/baseUrl'
import { HttpGet, HttpPut } from '@/network/servers'
import Utils from '@/utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import '../images/public/style.css'
import './index.scss'
const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getNowEnvironment,
  getNowToken,
  RemoveHTML,
  getQueryVariable
} = Utils


const requireContext = require.context("../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
  let str = item.replace('./', "").replace('.svg', "")
  fileObj[str] = svgs[index]
})


function App(props) {

  let {
    noticeAddr,
    userInfo,
    env,
    baseUrl
  } = props



  const getToken = () => {
    if (getQueryVariable('env') === 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }


  const [detail, setDetail] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);
  const [noticeId, setNoticeId] = useState("");
  const [taskId, setTaskId] = useState('')

  const [isRead, setIsRead] = useState(0);
  const [type, setType] = useState('0');
  const [height, setHeight] = useState(0);

  const getCommonData = () => {
    if (Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面
        requestSystemUrl('200').then((response) => {
          HttpGet({
            url: response + `/PsnMgr/Common/GetUserAndSchoolInfo?Token=${getQueryVariable('lg_tk')}`,
            data: {},
            header: {
              Authorization: 'X-Token=' + getQueryVariable('lg_tk')
            },
          }).then((result) => {
            let info = result.Data
            requestSystemUrl('220').then((res) => {
              let instance = Taro.getCurrentInstance()
              if (instance.router?.params) {
                let params = instance.router.params
                let id = params.id
                let taskReleaseId = params.taskReleaseId
                if (taskReleaseId == 'undefined') {
                  taskReleaseId = ''
                }
                setTaskId(taskReleaseId)
                setNoticeId(id)
                let fileUrl = res;
                let url = res + "/api/notice/info/receiver/read/detail"
                let { UserID, UserType, SchoolID } = info
                HttpGet({
                  url,
                  data: {
                    userId: UserID,
                    noticeId: id,
                    taskReleaseId: taskReleaseId || ''
                  },
                  load: true,
                }).then(res => {
                  if (res.code == 200 && res.data) {
                    let attachments = res.data.attachments
                    if (attachments && attachments.length !== 0) {
                      let imgArr = [] as any, fileArr = [] as any
                      attachments.map(item => {
                        item.url = fileUrl + '/upload/' + item.url.split('/upload/')[1]
                        let fileType = Utils.getFileType(item.name)
                        if (fileType == 'img') {
                          imgArr.push(item)
                        } else {
                          fileArr.push(item)
                        }
                      })

                      setFileList(fileArr)
                      setImgList(imgArr)
                    }
                    setIsRead(res.data.readStatus)
                    setDetail(res.data)
                  } else {
                    Taro.showToast({
                      title: res.msg,
                      icon: 'none'
                    })
                  }
                })
              }
            })
          })
        })
      } else {
        //应用内跳转
        let instance = Taro.getCurrentInstance()
        if (instance.router?.params) {
          let params = instance.router.params
          let id = params.id
          let taskReleaseId = params.taskReleaseId
          if (taskReleaseId == 'undefined') {
            taskReleaseId = ''
          }
          setTaskId(taskReleaseId)
          setNoticeId(id)
          let url = noticeAddr + "/api/notice/info/receiver/read/detail"
          let { UserID, UserType, SchoolID } = userInfo
          HttpGet({
            url,
            data: {
              userId: UserID,
              noticeId: id,
              taskReleaseId: taskReleaseId || ''
            },
            load: true
          }).then(res => {
            if (res.code == 200 && res.data) {
              let attachments = res.data.attachments
              if (attachments && attachments.length !== 0) {
                let imgArr = [], fileArr = []
                attachments.map(item => {
                  item.url = noticeAddr + '/upload/' + item.url.split('/upload/')[1]
                  let fileType = Utils.getFileType(item.name)
                  if (fileType == 'img') {
                    imgArr.push(item)
                  } else {
                    fileArr.push(item)
                  }
                })

                setFileList(fileArr)
                setImgList(imgArr)
              }
              setIsRead(res.data.readStatus)
              setDetail(res.data)
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          })
        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()

      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params) {
        let params = instance.router.params
        let id = params.id
        let taskReleaseId = params.taskReleaseId
        if (taskReleaseId == 'undefined') {
          taskReleaseId = ''
        }
        // console.log(params);

        setIsRead(isRead)
        setNoticeId(id)
        setTaskId(taskReleaseId)

        HttpGet({
          url: '/api/commons/users/info',
          data: {
            token: getNowToken()
          }
        }).then((res1) => {
          let { userId, UserType, SchoolID } = res1.data
          HttpGet({
            url: 'api/commons/system/getServerInfo',
            data: {
              sysIds: '220',
            },
          }).then((response) => {
            let url = response.data[0].webSvrAddr + "/api/notice/info/receiver/read/detail"
            HttpGet({
              url,
              data: {
                userId,
                noticeId: id,
                taskReleaseId: taskReleaseId || ''
              }
            }).then(res => {
              if (res.code == 200 && res.data) {
                let attachments = res.data.attachments
                if (attachments && attachments.length !== 0) {
                  let imgArr = [], fileArr = []
                  attachments.map(item => {
                    let fileType = Utils.getFileType(item.name)
                    if (fileType == 'img') {
                      imgArr.push(item)
                    } else {
                      fileArr.push(item)
                    }
                  })

                  setFileList(fileArr)
                  setImgList(imgArr)
                }
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    }
  }

  const hasRead = () => {
    let { UserID } = userInfo

    let url

    url = noticeAddr + `/api/notice/receiver/reply?userId=${UserID}&noticeId=${noticeId}&taskReleaseId=${taskId}`
    HttpPut({
      url,
    }).then(response => {
      if (response.code == 200) {
        Taro.showToast({
          title: "已阅"
        })
        setIsRead(1)
      } else {
        Taro.showToast({
          title: response.msg,
          icon: 'none'
        })
      }
    })

  }

  const download = async (item, index) => {
    let url = item.url
    if (window.__wxjs_environment === 'miniprogram') {
      const params = await getWxSDKParams([])
      wx.config(params);
      try {
        browserController.openFileForWebview(wx, { fileUrl: url })
      } catch (error) {
        Taro.showToast({ title: err, icon: 'none' })
      }
    } else {
      let arr = fileList.concat([])
      net.downloadFile({
        url,
        fileName: item.name,
        onProgress: process => {
          Taro.showToast({
            icon: 'loading',
            title: `正在下载${process}`
          })
        },
        onSuccess: path => {
          Taro.showToast({
            title: '下载成功',
            icon: 'success',
            duration: 2000

          })
          arr[index].preView = true
          storage.set(item.attachmentId, path)
          setFileList(arr)
        },
        onError: error => {
          Taro.showToast({
            title: '下载失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  }

  const showPreView = (item) => {
    let arr = []
    imgList.map(t => {
      arr.push(t.url)
    })
    Taro.previewImage({
      current: item.url, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  }

  const goBack = () => {
    Taro.redirectTo({
      url: '/pages/messageApp/index'
    })
  }

  const showFile = (item) => {
    browserController.openFileReader(storage.get(item.attachmentId))
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    document.title = '通知详情'
    if (window.__wxjs_environment === 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    return () => {
      if (Utils.getSystemInfo() === 'weapp') {
        document.title = '消息'
        window.getNoticeList && typeof window.getNoticeList === 'function' && window.getNoticeList()
      }
    }
  }, []);

  return (
    <View className="noticeDetail">
          <Header
            title='通知详情'
            isBlod={false}
            isLeft={true}
            goback={Current.router?.params.from ? goBack : ()=>{}}
          />
      {
        detail ?
          <View className="header">
            <View className="title">{detail.title}</View>
            <View className="noticeInfo">
              <Text>{detail?.taskReleaseTime || detail.releaseTime}</Text>
              <Text style={{ margin: '0 10px', color: '#999999' }}>|</Text>
              <Text>{detail.userName}</Text>
              {
                typeof detail.readCount == 'number' ? <Text >|</Text> : null
              }
              {
                typeof detail.readCount == 'number' ? <Text>{detail.readCount || 0}(已阅)</Text> : null
              }
            </View>
          </View> : null
      }

      {
        detail ?
          (!getNowEnvironment() ? <View className="content" dangerouslySetInnerHTML={{ __html: detail.content }}></View> :
            <View className="content">{RemoveHTML(detail.content)}</View>
          ) : null
      }
      {
        <View className="attachment">
          <View className="imgBox">
            {
              imgList.map(item => {
                return (
                  <View className="imgItem" onClick={() => showPreView(item)}>
                    <Image className="imgSrc" src={item.url} mode='aspectFill' />
                  </View>
                )
              })
            }
          </View>
          <View className="fileBox">
            {
              fileList.map((item, index) => {
                let icon = Utils.getFileType(decodeURIComponent(item.name))
                let fileIcon = {
                  "img": "0a00901",
                  "doc": "0a00101",
                  "ppt": "0a00201",
                  "pdf": "0a00501",
                  "txt": "0a00401",
                  "xls": "0a00301",
                  "music": "0a00601",
                  "video": "0a00701",
                  "html": "0a01001",
                  "zip": "0a01201",
                  "otr": "0a01101"
                }
                let src = fileObj[fileIcon[icon]]
                // console.log(`fileObj`, fileObj['0a00101'])
                // console.log(`src`, fileIcon[icon])
                let size = Utils.getFileSize(item.size)
                return (
                  <View className="docItem">
                    <View className="docIcon">
                      <Image className="docImg" src={src} />
                    </View>
                    <View className="docInfo">
                      <View className="docName oneline">{decodeURIComponent(item.name)}</View>
                      <View className="docSize">{size}</View>
                    </View>
                    {
                      (storage.get(item.attachmentId) || item.preView) ?
                        <View className="preViewFile" onClick={() => showFile(item)}>
                          <Text>查看</Text>
                        </View>
                        :
                        <View
                          className="downLoadIcon_content"
                          onClick={() => download(item, index)}
                          style={Utils.getNowEnvironment() ? { width: '32px', height: '32px' } : ''}
                        >
                        </View>
                    }

                  </View>
                )
              })
            }
          </View>
        </View>
      }
      {detail ?
        (detail.readType == 2 && detail.readStatus == 0?
          <View className="hasReadBox">
            <LgButton onClick={hasRead} type='B' width="640"> 已阅 </LgButton>
          </View> : null) : ""
      }
    </View>
  )
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl
  }
}

export default connect(mainProps)(App);
